<?php

namespace app\merchant\controller;

use app\admin\model\Goods as ModelGoods;
use app\admin\model\MerchantAccount;
use app\admin\model\MerchantNotice;
use app\admin\model\ShippingRule;
use app\admin\model\ShippingTemplate;
use app\admin\model\UserMerchant;
use think\facade\View;
use app\common\services\RedisService;
use app\common\Tools;
use app\Request;
use think\facade\Db;

class Store extends Base 
{
   
    public function store_info(){
        $merchant         = UserMerchant::find($this->uid);
        view::assign('merchant', $merchant);
        return View::fetch();
    }

    public function store_notice(){
        $merchant         = UserMerchant::find($this->uid);
        view::assign('merchant', $merchant);
        return View::fetch();
    }

    public function store_model(){
        $template = ShippingTemplate::with(['rules'])->where('merchant_id', $this->uid)->order('id desc')->find();
        view::assign('template', $template);
        return View::fetch();
    }

    public function account_info(){
        $merchant         = UserMerchant::find($this->uid);
        view::assign('merchant', $merchant);
        return View::fetch();
    }

    public function account_pwd(){
        $merchant         = UserMerchant::find($this->uid);
        view::assign('merchant', $merchant);
        return View::fetch();
    }

    public function trade_account_pwd(){
        $merchant         = UserMerchant::find($this->uid);
        $merchant_account = MerchantAccount::where('merchant_id', $this->uid)->find();
        view::assign('merchant', $merchant);
        view::assign('merchant_account', $merchant_account);
         // 获取商户的收款账号
        return View::fetch();
    }
    
    //保存
    public function save_store_info(Request $request){
        $redis_service = RedisService::getInstance();
        $lock_key = "api:save_store_info:" . $this->uid;
        try {
            $action_lock = $redis_service->acquireLock($lock_key, 3); // 原子设置+过期时间
            if (!$action_lock) {
                exception('请勿重复提交');
            }
            $post_data = $request->postMore([
                ['shop_thumb', ''],
                ['shop_name', ''],
                ['shop_info', ''],
                ['phone', ''],
                ['email', ''],
            ]);
            $merchant = UserMerchant::find($this->uid);
            if (!$merchant) {
                exception('商户不存在');
            }
            $merchant->shop_thumb = $post_data['shop_thumb'];
            $merchant->shop_name = $post_data['shop_name'];
            $merchant->shop_info = $post_data['shop_info'];
            $merchant->phone = $post_data['phone'];
            $merchant->email = $post_data['email'];
            $merchant->save();
        } catch (\Exception $e) {
            return app('json')->fail($e->getMessage());

        } finally {
            // 🧹 无论成功与否，释放锁
            $redis_service->releaseLock($lock_key);
        }

        return app('json')->success('操作成功');
    }

    //修改登录密码
    public function update_login_pwd(Request $request){
        $redis_service = RedisService::getInstance();
        $lock_key = "api:save_store_info:" . $this->uid;
        try {
            $action_lock = $redis_service->acquireLock($lock_key, 3); // 原子设置+过期时间
            if (!$action_lock) {
                exception('请勿重复提交');
            }
            $post_data = $request->postMore([
                ['old_password', ''],
                ['new_password', ''],
                ['confirm_password', ''],
            ]);
            Tools::check($post_data, [
                'old_password' => 'require',
                'new_password' => 'require',
                'confirm_password' => 'require',
            ], [
                'old_password.require' => '旧密码不得为空',
                'new_password.require' => '新密码不得为空',
                'confirm_password.require' => '请确认密码',
            ]);
            if ($post_data['new_password'] !== $post_data['confirm_password']) {
                exception('两次密码输入不一致');
            }
            $merchant = UserMerchant::find($this->uid);
            if (!$merchant) {
                exception('商户不存在');
            }
            if($post_data['old_password'] == $post_data['new_password']){
                exception('新密码不能与旧密码相同');
            }
            if($merchant->password !== md5(sha1($post_data['old_password']))) {
                exception('密码不正确');
            }
            $merchant->password = md5(sha1($post_data['new_password']));
            $merchant->save();
        } catch (\Exception $e) {
            return app('json')->fail($e->getMessage());

        } finally {
            // 🧹 无论成功与否，释放锁
            $redis_service->releaseLock($lock_key);
        }

        return app('json')->success('操作成功');
    }

    //更新交易密码
    public function update_trade_pwd(Request $request){
        $redis_service = RedisService::getInstance();
        $lock_key = "api:update_trade_pwd:" . $this->uid;
        try {
            $action_lock = $redis_service->acquireLock($lock_key, 3); // 原子设置+过期时间
            if (!$action_lock) {
                exception('请勿重复提交');
            }
            $post_data = $request->postMore([
                ['old_password', ''],
                ['new_password', ''],
                ['confirm_password', ''],
            ]);
            Tools::check($post_data, [
                'old_password' => 'require',
                'new_password' => 'require',
                'confirm_password' => 'require',
            ], [
                'old_password.require' => '旧密码不得为空',
                'new_password.require' => '新密码不得为空',
                'confirm_password.require' => '请确认密码',
            ]);
            if ($post_data['new_password'] !== $post_data['confirm_password']) {
                exception('两次密码输入不一致');
            }
            $merchant = MerchantAccount::where('merchant_id', $this->uid)->find();
            if (!$merchant) {
                exception('商户账号不存在');
            }
            if($post_data['old_password'] == $post_data['new_password']){
                exception('新密码不能与旧密码相同');
            }
            if($merchant->password !== md5(($post_data['old_password']))) {
                exception('密码不正确');
            }
            $merchant->password = md5(($post_data['new_password']));
            $merchant->save();
        } catch (\Exception $e) {
            return app('json')->fail($e->getMessage());

        } finally {
            // 🧹 无论成功与否，释放锁
            $redis_service->releaseLock($lock_key);
        }

        return app('json')->success('操作成功');
    }

    //新增店铺公告
    public function add_store_notice(Request $request){
        $redis_service = RedisService::getInstance();
        $lock_key = "api:add_store_notice:" . $this->uid;
        try {
            $action_lock = $redis_service->acquireLock($lock_key, 3); // 原子设置+过期时间
            if (!$action_lock) {
                exception('请勿重复提交');
            }
            $post_data = $request->postMore([
                ['content', ''],
            ]);
            Tools::check($post_data, [
                'content' => 'require',
            ], [
                'content.require' => '内容不得为空',
            ]);
            MerchantNotice::create([
                'merchant_id' => $this->uid,
                'content' => $post_data['content'],
            ]);
            
        } catch (\Exception $e) {
            return app('json')->fail($e->getMessage());

        } finally {
            // 🧹 无论成功与否，释放锁
            $redis_service->releaseLock($lock_key);
        }

        return app('json')->success('操作成功');
    }

    //删除公告
    public function delete_store_notice(Request $request){
        $redis_service = RedisService::getInstance();
        $lock_key = "api:delete_store_notice:" . $this->uid;
        try {
            $action_lock = $redis_service->acquireLock($lock_key, 3); // 原子设置+过期时间
            if (!$action_lock) {
                exception('请勿重复提交');
            }
            $post_data = $request->postMore([
                ['id', ''],
            ]);
            Tools::check($post_data, [
                'id' => 'require',
            ], [
                'id.require' => 'ID不得为空',
            ]);
            $notice = MerchantNotice::where('merchant_id', $this->uid)->where('id', $post_data['id'])->find();
            if (!$notice) {
                exception('公告不存在');
            }
            $notice->delete();
            
        } catch (\Exception $e) {
            return app('json')->fail($e->getMessage());

        } finally {
            // 🧹 无论成功与否，释放锁
            $redis_service->releaseLock($lock_key);
        }

        return app('json')->success('操作成功');
    }

    

    //消息列表
    public function get_store_notice(Request $request){
        $post_data = $request->getMore([
            ['page', 1],
            ['limit', 10],
        ]);
        $query = MerchantNotice::where('merchant_id', $this->uid);
        $count = $query->count();
        $list = $query->page($post_data['page'], $post_data['limit'])->order('id desc')->select()->toArray();

        return app('json')->layuiTableResponse('ok',$list,$count);
    }


    public function get_region_data(){
        $regions = Db::name('city_area')
            ->field('id, parent_id, name as title')
            ->where('level', '=', 1) // 只取省和市
            ->select()
            ->toArray();
            
        $tree = [];
        foreach($regions as $region){
            if($region['parent_id'] == 0){
                $tree[$region['id']] = [
                    'id' => $region['id'],
                    'title' => $region['title'],
                    'children' => []
                ];
            } else {
                if(isset($tree[$region['parent_id']])){
                    $tree[$region['parent_id']]['children'][] = [
                        'id' => $region['id'],
                        'title' => $region['title']
                    ];
                }
            }
        }
        
        return json([
            'code' => 0,
            'data' => array_values($tree)
        ]);
    }


    //运费模板保存
    public function shipping_template_save(Request $request){
        $redis_service = RedisService::getInstance();
        $lock_key = "api:shipping_template_save:" . $this->uid;
        Db::startTrans(); // 开启事务
        try {
            $action_lock = $redis_service->acquireLock($lock_key, 3); // 原子设置+过期时间
            if (!$action_lock) {
                exception('请勿重复提交');
            }
            $data = $request->post();
        
            // 验证数据
            if(empty($data['name'])){
                exception('模板名称不能为空');
            }
            
            if(!isset($data['type']) || !in_array($data['type'], [1,2,3])){
                exception('请选择正确的计价方式'); 
            }
            
            if(empty($data['rules']) || !is_array($data['rules'])){
                exception('请至少添加一个配送区域'); 
            }
            
            // 准备模板数据
            $templateData = [
                'name'             => $data['name'],
                'type'             => $data['type'],
                'is_free_shipping' => isset($data['is_free_shipping']) ? 1 : 0,
                'is_default'       => isset($data['is_default']) ? 1 : 0,
                'merchant_id'      => $this->uid,
                'update_time'      => time()
            ];
            $merhant_tempalte = Db::name('shipping_template')
                ->where('merchant_id', $this->uid)
                ->where('is_default', 1)
                ->find();
            // 如果是编辑
            if($merhant_tempalte){
                $templateId = $merhant_tempalte['id'];
                Db::name('shipping_template')
                    ->where('id', $templateId)
                    ->where('merchant_id', $this->uid)
                    ->update($templateData);
                    
                // 删除旧规则
                Db::name('shipping_rule')
                    ->where('template_id', $templateId)
                    ->delete();
            } 
            // 如果是新增
            else {
                $templateData['create_time'] = time();
                $templateId = Db::name('shipping_template')
                    ->insertGetId($templateData);
            }
            
            // 保存规则
            foreach($data['rules'] as $rule){
                Db::name('shipping_rule')->insert([
                    'template_id' => $templateId,
                    'region_ids' => $rule['region_ids'],
                    'region_names' => $rule['region_names'],
                    'first_unit' => $rule['first_unit'],
                    'first_price' => $rule['first_price'],
                    'continue_unit' => $rule['continue_unit'],
                    'continue_price' => $rule['continue_price'],
                    'create_time' => time()
                ]);
            }
            
            // 如果是默认模板，取消其他默认
            if(isset($data['is_default']) && $data['is_default'] == 1){
                Db::table('original_shipping_template')
                    ->where('id', '<>', $templateId)
                    ->update(['is_default' => 0]);
            }
                Db::commit();
        } catch (\Exception $e) {
                 Db::rollback();
            return app('json')->fail($e->getMessage());

        } finally {
            // 🧹 无论成功与否，释放锁
            $redis_service->releaseLock($lock_key);
        }

        return app('json')->success('操作成功');
    }
}
